import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
const CATCH_URLS = ['m.ctrip.com/', 'm.ctrip.com/html5/', 'm.ctrip.com/html5'];

class WebView extends StatefulWidget {
  final String url;
  final String statusBarColor;
  final String title;
  final bool hideAppBar;
  final bool backForbid;

  WebView({required this.url, required this.statusBarColor, required this.title, required this.hideAppBar,
    this.backForbid=false});

  @override
  _WebViewSate createState() {
    return _WebViewSate();
  }
  // _WebViewSate createState() => _WebViewSate();

}

class _WebViewSate extends State<WebView> {
  final webviewReference = FlutterWebviewPlugin();
  late StreamSubscription<String> _onUrlChanged;
  late StreamSubscription<WebViewStateChanged> _onStateChanged;
  late StreamSubscription<WebViewHttpError> _onHttpError;
  bool exiting = false;

  @override
  void initState() {
    super.initState();
    webviewReference.close(); // 防止页面重复打开
    _onUrlChanged = webviewReference.onUrlChanged.listen((String url) {});
    _onStateChanged =
        webviewReference.onStateChanged.listen((WebViewStateChanged state) {
      switch (state.type) {
        case WebViewState.startLoad:
          if(_isToMain(state.url) && !exiting){
            if(widget.backForbid){
              webviewReference.launch(widget.url);
            }else{
              Navigator.pop(context);
              exiting=true;
            }
          }
          break;
        default:
          break;
      }
    });
    _onHttpError =
        webviewReference.onHttpError.listen((WebViewHttpError error) {
      print(error);
    });
  }

  _isToMain(String url) {
     bool contain = false;
     for(final value in CATCH_URLS) {
       if(url.endsWith(value)) {
         contain = true;
         break;
       }
     }
     return contain;
  }

  @override
  void dispose() {
    super.dispose();
    _onUrlChanged.cancel();
    _onStateChanged.cancel();
    _onHttpError.cancel();
    webviewReference.dispose();
  }

  @override
  Widget build(BuildContext context) {
    String statusBarColorStr = widget.statusBarColor;
    Color backButtonColor;
    if(statusBarColorStr == 'ffffff') {
      backButtonColor = Colors.black;
    }else{
      backButtonColor = Colors.white;
    }
    return Scaffold(
        body: Column(
      children: <Widget>[
        // 把String的颜色转换为Color的颜色
        _appBar(Color(int.parse('0xff'+statusBarColorStr)), backButtonColor),
        // 下面要展示的内容撑满界面
        Expanded(child: WebviewScaffold(
          url: widget.url,
          withZoom: true,
          withLocalStorage: true,
          hidden: true,
          initialChild: Container(
            color: Colors.white,
            child: Center(
              child: Text('Waiting...'),
            ),
          ),
        ))
      ],
    ));
  }

  _appBar(Color backgroundColor, Color backButtonColor) {
    // 隐藏状态下的appBar
    // ?? 语法糖，左边如果为空返回右边的值，否则不处理
    if (widget.hideAppBar) {
      return Container(
        color: backgroundColor,
        height: 30,
      );
    }
    return Container(
      // 撑满
      child: FractionallySizedBox(
        widthFactor: 1,
        child: Stack(
          children: <Widget>[
            // 可点击的
            GestureDetector(
              child: Container(
                margin: EdgeInsets.only(left: 10),
                child: Icon(
                  Icons.close,
                  color: backButtonColor,
                  size: 26,
                ),
              ),
            ),
            // 绝对定位设置标题
            Positioned(
                left: 0,
                right: 0,
                child: Center(
                  child: Text(widget.title,
                      style: TextStyle(color: backButtonColor, fontSize: 20)),
                ))
          ],
        ),
      ),
    );
  }
}
